/*
 * @Autor: dingxiaolin
 * @Date: 2020-05-05 18:56:48
 * @LastEditors: dingxiaolin
 * @LastEditTime: 2020-05-05 20:10:31
 */
const domain = "api.dingxiaolin.com:8080"
// const domain = "tl.mofangdegisn.cn:8080"
const deviceId = "49085607-148B-4E4E-B624-27217A328E31"
var testWs = function () {
    const ws = new WebSocket('ws://' + domain);
    var now = new Date();

    var reg = {
        method: 'GET',
        host: domain,
        querys: {
            'id': deviceId,
        },
        headers: {
            'x-ca-websocket_api_type': ['REGISTER'],
            'x-ca-seq': ['0'],
            // 'x-ca-nonce': [uuid.v4().toString()],
            'date': [now.toUTCString()],
            'x-ca-timestamp': [now.getTime().toString()],
            'CA_VERSION': ['1'],
        },
        path: '/register',
        body: 'ssfss',
    };

    ws.onopen = function open() {
        console.log('open:');
        ws.send('RG#' + deviceId);
    };

    var registered = false;
    var hbStarted = false;

    ws.onmessage = function incoming(event) {
        console.log('data:');
        console.log(event.data);

        if (event.data.startsWith('NF#')) {
            var msg = JSON.parse(event.data.substr(3));
            // app.addHistory(
            //     util.format('%s (%s) %s',
            //         Prompt, msg.from,
            //         decodeURIComponent(msg.message.toString())));
            // app.setState({ 'prompt': Prompt });
        }

        if (!registered) {
            registered = true;
            ws.send(JSON.stringify(reg));
        }

        if (!hbStarted && event.data.startsWith('RO#')) {
            hbStarted = true;
            setInterval(function () {
                ws.send('H1');
            }, 15 * 1000);
        }
    };
};

testWs();